// pages/order-detail/order-detail.js
import { hideLoading, msg, showLoading, navTo } from "@/utils/util"

Page({

    data: {
        orderId: '',
        order: {}, //订单信息
    },

    onLoad(options) {
        const {orderId} = options
        this.setData({ orderId })
        this.loadOrder()
    },

    onPullDownRefresh() {
        this.loadOrder()
    },

    navTo, 

    // 查询订单详情
    async loadOrder() {
        try {
            showLoading()

            const {orderId} = this.data
            const {data} = await wx.cloud.database().collection('mxg_order')
                .doc(orderId).get()
            console.log("data", data)

            this.setData({order: data})

        } catch (error) {
            console.error("订单详情查询失败", error)
            msg('订单详情查询失败')
        } finally {
            hideLoading()
            wx.stopPullDownRefresh()
        }
    },

    // 门店指引：打开地图
    handleOpenLocation() {
        const { name, address, location = {} } = this.data.order?.shop
        const {longitude, latitude} = location
        console.log('name', name, address, longitude, latitude)
        if (!longitude || !latitude) {
            return msg('门店没有地图位置')
        }

        // 打开地图
        wx.openLocation({
            longitude,
            latitude,
            name,
            address
        })

    },

    // 取消订单
    async handleCancelOrder() {
        const { cancel } = await wx.showModal({
          title: '取消订单',
          content: '取消后，需要重新选择商品下单',
          cancelText: '取消订单',
          confirmText: '再考虑下',
          cancelColor: '#333',
          confirmColor: '#e40030'
        })
        // console.log(cancel)
        if (cancel) {
            this.updateOrderCancel()
        }
    },

    // 更新订单为已取消状态
    async updateOrderCancel() {
        try {
            showLoading('取消中', {mask: true})

            const updated = await wx.cloud.database().collection('mxg_order')
                .doc(this.data.orderId)
                .update({
                    data: {
                        state: 4, // 1 等待支付，2 已支付，3已完成，4已取消
                        _updateTime: Date.now()
                    }
                })
            msg('订单已取消')
            wx.startPullDownRefresh()
        } catch (error) {
            console.error('订单取消失败', error)
            msg('订单取消失败', {icon: 'error'})
        } finally {
            hideLoading()
        }
    }

})